package 练习11_线程池综合使用案例;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName: ThreadPoolStudy01
 * @Author: AllenSun
 * @Date: 2025/10/23 23:17
 */
public class ThreadPoolStudy02_submit {
    public static void main(String[] args) {
        UserAccount zhangsan = new UserAccount("张三",100);
        UserAccount lisi = new UserAccount("李四",0);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        double amount = 1;

        for (int i = 0; i < 103; i++) {

            executorService.submit(()->{
                try {
                    transfer02(zhangsan,lisi,amount);
                } catch (Exception e) {
                    System.out.println("捕捉到报错信息："+e.getMessage());
                    throw new RuntimeException(e);
                }
            });

        }


    }

    public static void transfer02(UserAccount from,UserAccount to,double amount) throws InterruptedException {
        synchronized (UserAccount.class) {
            double fromBalance = from.getBalance();
            double toBalance = to.getBalance();
            if (fromBalance >= amount) {
                from.setBalance(fromBalance - amount);
                Thread.sleep(100);
                to.setBalance(toBalance + amount);
                System.out.println("当前线程："+Thread.currentThread().getName()+"；转出账户：" + from.getUserName() + "，余额：" + from.getBalance()+"；转入账户：" + to.getUserName() + "，余额：" + to.getBalance());
            } else {
                System.out.println("当前线程："+Thread.currentThread().getName()+"；余额不足");
                throw new RuntimeException("抛出异常余额不足");
            }
        }
    }
}
